package com.pansoft.mobilefitness.fragment;

import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import androidx.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.core.xml.StubObject;
import com.efounder.chat.event.RightTopMenuClickEvent;
import com.efounder.frame.baseui.BaseContract;
import com.efounder.frame.baseui.BasePresenterFragment;
import com.efounder.utils.JfResourceUtil;
import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.AxisBase;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.formatter.IAxisValueFormatter;
import com.github.mikephil.charting.formatter.IFillFormatter;
import com.github.mikephil.charting.highlight.Highlight;
import com.github.mikephil.charting.interfaces.dataprovider.LineDataProvider;
import com.github.mikephil.charting.interfaces.datasets.ILineDataSet;
import com.github.mikephil.charting.listener.OnChartValueSelectedListener;
import com.github.mikephil.charting.utils.Utils;
import com.nineoldandroid.animation.ObjectAnimator;
import com.nineoldandroid.animation.ValueAnimator;
import com.pansoft.mobilefitness.R;
import com.pansoft.mobilefitness.view.CircleBar;
import com.pansoft.mobilefitness.view.MotionCrcle;
import com.pansoft.mobilefitness.view.MyMarkerView;
import com.pansoft.mobilefitness.view.PopManager;
import com.utilcode.util.ConvertUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;

/**
 * @author : zzj
 * @e-mail : zhangzhijun@pansoft.com
 * @date : 2019/1/28 16:26
 * @desc :  健康首页
 * @version: 1.0
 */
public class HealthHomeFragment extends BasePresenterFragment implements OnChartValueSelectedListener {

    private CircleBar circleBar;
    private LineChart chart;
    private TextView tv_distance;
    private TextView tv_heat_kcal;
    private TextView tv_heart_rate;
    private TextView tv_watch_connect_hint;
    private MotionCrcle mCrcle;

    public static HealthHomeFragment newInstance() {

        Bundle args = new Bundle();

        HealthHomeFragment fragment = new HealthHomeFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        EventBus.getDefault().register(this);
        return super.onCreateView(inflater, container, savedInstanceState);
    }

    @Override
    public void onDestroyView() {
        EventBus.getDefault().unregister(this);

        super.onDestroyView();
    }

    @Override
    protected BaseContract.BasePresenter initPresenter() {
        return null;
    }

    @Override
    protected int getContentLayoutId() {
        return R.layout.health_fragment_home;
    }

    @Override
    protected void initView(View root) {
        chart = root.findViewById(R.id.line_chart);
        circleBar = root.findViewById(R.id.circleBar);
        tv_distance = root.findViewById(R.id.tv_distance);
        tv_heat_kcal = root.findViewById(R.id.tv_heat_kcal);
        tv_heart_rate = root.findViewById(R.id.tv_heart_rate);
        tv_watch_connect_hint = root.findViewById(R.id.tv_watch_connect_hint);
        circleBar.setProgress(76, true);
        circleBar.setText(8537);
//        circleBar.startCustomAnimation();
        initLineChart();
        setData(26, 500);
        tv_watch_connect_hint.setText(com.efounder.utils.Utils.matcherSearchText(JfResourceUtil.getSkinColor(R.color.fitness_text_content_orange)
                , getResources().getString(R.string.health_home_watch_connect_hint), new String[]{"Smart Watch", "72%"}));
        tv_distance.setText(com.efounder.utils.Utils.matcherSearchTextSize(JfResourceUtil.getSkinColor(R.color.light_text_color)
                , ConvertUtils.dp2px(12), getResources().getString(R.string.health_home_distance_km), new String[]{"KM"}));
        tv_heat_kcal.setText(com.efounder.utils.Utils.matcherSearchTextSize(JfResourceUtil.getSkinColor(R.color.light_text_color)
                , ConvertUtils.dp2px(12), getResources().getString(R.string.health_home_heat_kcal), new String[]{"KCAL"}));
        tv_heart_rate.setText(com.efounder.utils.Utils.matcherSearchTextSize(JfResourceUtil.getSkinColor(R.color.light_text_color)
                , ConvertUtils.dp2px(12), getResources().getString(R.string.health_home_heart_rate_bpm), new String[]{"BPM"}));

        mCrcle = (MotionCrcle) root.findViewById(R.id.motion_crcle_foot);
        mCrcle.setmMaxSteps(10000);
        final ValueAnimator animator = ObjectAnimator.ofFloat(0, 2000);
        animator.setDuration(1000);
        animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator valueAnimator) {
                float value = (float) valueAnimator.getAnimatedValue();
                mCrcle.setmCurrentSteps((int) value);
            }
        });
        animator.start();

        circleBar.setUpAndDownColor(JfResourceUtil.getSkinColor(R.color.light_text_color));
        circleBar.setDownSecondColor(JfResourceUtil.getSkinColor(R.color.black_text_color));
    }


    private void initLineChart() {
        // background color

        // disable description text
        chart.getDescription().setEnabled(false);

        // enable touch gestures
        chart.setTouchEnabled(true);

        // set listeners
        chart.setOnChartValueSelectedListener(this);
        chart.setDrawGridBackground(false);

        // create marker to display box when values are selected
        MyMarkerView mv = new MyMarkerView(mActivity, R.layout.custom_marker_view);
        // Set the marker to the chart
        mv.setChartView(chart);
        chart.setMarker(mv);

        // enable scaling and dragging
        chart.setDragEnabled(true);
        chart.setScaleEnabled(false);

        // force pinch zoom along both axis
        chart.setPinchZoom(false);

        final XAxis xAxis = chart.getXAxis();
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        xAxis.setDrawLabels(true);
        xAxis.setLabelCount(6);
        xAxis.setDrawAxisLine(false);
        xAxis.setDrawGridLines(false);

        xAxis.setTextColor(JfResourceUtil.getSkinColor(R.color.black_text_color));
        xAxis.setValueFormatter(new IAxisValueFormatter() {
            @Override
            public String getFormattedValue(float value, AxisBase axis) {
                String time = "";
                int xValue = (int) value;
                if (xValue < 10) {
                    time = "0" + xValue + ":00";
                } else {
                    time = xValue + ":00";
                }
                return time;
            }
        });

        YAxis yAxisLeft = chart.getAxisLeft();
        YAxis yAxisRight = chart.getAxisRight();
        yAxisLeft.setEnabled(true);
        yAxisLeft.setDrawGridLines(false);
        yAxisLeft.setLabelCount(4);
        yAxisRight.setEnabled(false);
        yAxisLeft.setDrawAxisLine(false);
        yAxisRight.setDrawAxisLine(false);
        //设置最大值至TOP顶端的距离
        yAxisLeft.setSpaceTop(30f);
        yAxisRight.setSpaceTop(30f);
        yAxisLeft.setTextColor(JfResourceUtil.getSkinColor(R.color.black_text_color));
        //图例
        Legend l = chart.getLegend();
        l.setEnabled(false);
    }


    private void setData(int count, float range) {

        ArrayList<Entry> values = new ArrayList<>();

        for (int i = 0; i < count; i++) {

            float val = (float) (Math.random() * range);
            values.add(new Entry(i, val));
        }

        LineDataSet set1;

        if (chart.getData() != null &&
                chart.getData().getDataSetCount() > 0) {
            set1 = (LineDataSet) chart.getData().getDataSetByIndex(0);
            set1.setValues(values);
            set1.notifyDataSetChanged();
            chart.getData().notifyDataChanged();
            chart.notifyDataSetChanged();
        } else {
            // create a dataset and give it a type
            set1 = new LineDataSet(values, "");

            set1.setDrawIcons(false);

            // draw dashed line
//            set1.enableDashedLine(10f, 5f, 0f);

            // black lines and points
            set1.setColor(JfResourceUtil.getSkinColor(R.color.fitness_chart_line_blue));
            set1.setDrawCircles(false);
            set1.setDrawValues(false);

            set1.setMode(LineDataSet.Mode.CUBIC_BEZIER);
            // line thickness and point size
            set1.setLineWidth(1f);

            // draw points as solid circles
            set1.setDrawCircleHole(false);

            // customize legend entry
            set1.setFormLineWidth(1f);
//            set1.setFormLineDashEffect(new DashPathEffect(new float[]{10f, 5f}, 0f));
            set1.setFormSize(15.f);

            // text size of values
            set1.setValueTextSize(9f);

            // draw selection line as dashed
//            set1.enableDashedHighlightLine(10f, 5f, 0f);
            set1.setDrawHighlightIndicators(false);
            set1.setHighlightEnabled(true);

            // set the filled area
            set1.setDrawFilled(true);
            set1.setFillFormatter(new IFillFormatter() {
                @Override
                public float getFillLinePosition(ILineDataSet dataSet, LineDataProvider dataProvider) {
                    return chart.getAxisLeft().getAxisMinimum();
                }
            });

            // set color of filled area
            if (Utils.getSDKInt() >= 18) {
                // drawables only supported on api level 18 and above
                Drawable drawable = JfResourceUtil.getSkinDrawable(R.drawable.shape_fitness_active_statistics);

                set1.setFillDrawable(drawable);
            } else {
                set1.setFillColor(Color.BLACK);
            }

            ArrayList<ILineDataSet> dataSets = new ArrayList<>();
            dataSets.add(set1); // add the data sets

            // create a data object with the data sets
            LineData data = new LineData(dataSets);

            // set data
            chart.setData(data);
        }
    }

    @Override
    public void onValueSelected(Entry e, Highlight h) {

    }

    @Override
    public void onNothingSelected() {

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void showPopMenu1(RightTopMenuClickEvent event) {
        StubObject stubObject = event.getStubObject();
        if (stubObject.getString("AndroidShow", "").equals("com.pansoft.mobilefitness.fragment.HealthHomeFragment")) {
            PopManager.showPop(getActivity(), event.getView());
        }
    }
}
